/**
 * 
 */
package dao;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;


/**
 * @author zharikhin
 *
 */
public class AbstractJdbcDao {

    private final static Log LOGGER = LogFactory.getLog(AbstractJdbcDao.class);

    Properties props = new Properties();
    
    protected String driverName;
    protected String url;
    protected String login;
    protected String password;
    protected String propertyFile;

    Connection conn = null;
    BasicDataSource dataSource = null;

    public AbstractJdbcDao() {}

    public AbstractJdbcDao(String propertyFile) {

        try {
            props.loadFromXML(this.getClass().getClassLoader().getResourceAsStream(propertyFile));
            driverName = props.getProperty("driverName");
            url = props.getProperty("url");
            login = props.getProperty("login");
            password = props.getProperty("password");

        } catch (IOException e) {
            LOGGER.error("IOException", e);
        };
    }
 
    public Connection createConnection(){

        if (dataSource != null) {
            try {
                conn = dataSource.getConnection();
            } catch (SQLException e) {
                LOGGER.error("SQLException", e);
                e.printStackTrace();
            }
        }
        else{
            try {
                dataSource = new BasicDataSource();
                dataSource.setDriverClassName(driverName);
                dataSource.setUrl(url);
                dataSource.setUsername(login);
                dataSource.setPassword(password);
                conn = dataSource.getConnection();
                return conn;
                
            } catch (SQLException e) {
                LOGGER.error("SQLException", e);
                e.printStackTrace();
            }
        }
            return conn;
    }

}
